<template>
  <div style="height: 100vh; display: flex; flex-direction: column; background: #f5f5f5;">
    <!-- 顶部导航栏 - 固定高度 -->
    <div style="height: 80px; background: white; border-bottom: 1px solid #ddd; display: flex; align-items: center; padding: 0 30px; flex-shrink: 0;">
      <a-button type="link" @click="goBack" style="padding: 0; margin-right: 20px; font-size: 16px;">
        <LeftOutlined />
        返回
      </a-button>
      <h1 style="color: #1890ff; margin: 0; font-size: 24px;">个人中心</h1>
    </div>
    
    <!-- 主体内容 -->
    <div style="flex: 1; padding: 40px 20px; background: #f5f5f5; width: 100%; box-sizing: border-box;">
        <a-spin :spinning="loading" style="width: 100%; display: block;">
          
          <!-- 个人信息卡片 -->
          <div v-if="userInfo.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px; width: 100%;">
            <h2 style="margin: 0 0 30px 0; color: #333; font-size: 20px; text-align: left;">个人信息</h2>
            
            <div style="display: flex; align-items: flex-start; gap: 40px;">
              <!-- 头像区域 -->
              <div style="position: relative;">
                <a-upload
                  :show-upload-list="false"
                  :before-upload="handleUploadAvatar"
                  accept="image/*"
                >
                  <a-avatar :size="120" :src="userInfo.avatar" style="cursor: pointer;">
                    {{ userInfo.username?.charAt(0)?.toUpperCase() }}
                  </a-avatar>
                </a-upload>
                <div style="position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.6); border-radius: 50%; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center;">
                  <span style="color: white; font-size: 14px;">📷</span>
                </div>
              </div>
              
               <!-- 用户信息 -->
               <div style="flex: 1;">
                <div style="margin-bottom: 30px;">
                  <label style="display: block; margin-bottom: 8px; color: #666; font-size: 16px;">用户名</label>
                  <div style="display: flex; gap: 12px; align-items: center;">
                    <a-input 
                      v-model:value="editForm.username" 
                      placeholder="请输入用户名" 
                      size="large"
                      style="flex: 1;"
                    />
                    <a-button type="primary" @click="saveUserInfo" :loading="updateLoading">
                      保存
                    </a-button>
                  </div>
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                  <div>
                    <span style="color: #666; font-size: 16px;">角色：</span>
                    <a-tag :color="userInfo.role === 0 ? 'red' : 'blue'" style="margin-left: 8px;">
                      {{ userInfo.role === 0 ? '管理员' : '前台用户' }}
                    </a-tag>
                  </div>
                  <div>
                    <span style="color: #666; font-size: 16px;">状态：</span>
                    <a-tag :color="userInfo.status === 1 ? 'green' : 'red'" style="margin-left: 8px;">
                      {{ userInfo.status === 1 ? '启用' : '停用' }}
                    </a-tag>
                  </div>
                </div>
                <div style="color: #999; font-size: 14px;">
                  注册时间：{{ userInfo.createTime }}
                </div>
              </div>
            </div>
          </div>

          <!-- 功能区域卡片 -->
          <div v-if="userInfo.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;">
            <a-tabs default-active-key="password" tab-position="top" style="width: 100%;">
               <a-tab-pane key="password" tab="修改密码">
                 <div style="padding: 20px 0; width: 100%;">
                  <a-form
                    :model="passwordForm"
                    :rules="passwordRules"
                    @finish="handleChangePassword"
                    layout="vertical"
                    style="width: 100%;"
                  >
                    <a-form-item label="当前密码" name="oldPassword">
                      <a-input-password v-model:value="passwordForm.oldPassword" placeholder="请输入当前密码" size="large" />
                    </a-form-item>
                    
                    <a-form-item label="新密码" name="newPassword">
                      <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" size="large" />
                    </a-form-item>
                    
                    <a-form-item label="确认新密码" name="confirmPassword">
                      <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" size="large" />
                    </a-form-item>
                    
                    <a-form-item>
                      <a-button type="primary" html-type="submit" :loading="passwordLoading" size="large">
                        修改密码
                      </a-button>
                    </a-form-item>
                  </a-form>
                </div>
              </a-tab-pane>
               
               <a-tab-pane key="favorites" tab="我的收藏">
                 <div style="padding: 20px 0;">
                   <a-spin :spinning="favoritesLoading">
                     <div v-if="favorites.length > 0">
                       <a-row :gutter="[16, 16]">
                         <a-col :span="8" v-for="item in favorites" :key="item.id">
                           <a-card hoverable style="height: 200px; cursor: pointer;" @click="viewFavoriteDetail(item)">
                             <div style="height: 100%; display: flex; flex-direction: column; justify-content: space-between;">
                               <div>
                                 <h4 style="margin: 0 0 8px 0; color: #1890ff; font-size: 16px; font-weight: 600;">
                                   {{ item.caseId ? item.caseNumber : item.documentTitle }}
                                 </h4>
                                 <p style="margin: 0 0 8px 0; color: #666; font-size: 14px; line-height: 1.4;">
                                   {{ item.caseId ? item.parties : (item.content ? item.content.substring(0, 80) : '') }}
                                 </p>
                               </div>
                               <div style="display: flex; justify-content: space-between; align-items: center;">
                                 <a-tag :color="item.caseId ? 'blue' : 'green'">
                                   {{ item.caseId ? '案件' : '文档' }}
                                 </a-tag>
                                 <span style="font-size: 12px; color: #999;">{{ item.createTime }}</span>
                               </div>
                             </div>
                           </a-card>
                         </a-col>
                       </a-row>
                       
                       <div v-if="favoritesPagination.total > favoritesPagination.pageSize" style="text-align: center; margin-top: 20px;">
                         <a-pagination
                           v-model:current="favoritesPagination.current"
                           v-model:page-size="favoritesPagination.pageSize"
                           :total="favoritesPagination.total"
                           :show-size-changer="false"
                           :show-quick-jumper="true"
                           @change="loadFavorites"
                         />
                       </div>
                     </div>
                     
                     <div v-else style="text-align: center; padding: 40px; color: #999;">
                       <div style="font-size: 48px; margin-bottom: 16px;">📚</div>
                       <p>暂无收藏内容</p>
                     </div>
                   </a-spin>
                 </div>
               </a-tab-pane>
            </a-tabs>
          </div>
          
           <!-- 未登录提示 -->
           <div v-if="!userInfo.id && !loading" style="background: white; padding: 60px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); text-align: center;">
             <p style="font-size: 16px; color: #999; margin-bottom: 20px;">请先登录查看个人信息</p>
             <a-button type="primary" @click="goHome">返回首页</a-button>
           </div>
           
         </a-spin>
     </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getCurrentUserInfo, changePassword, updateUser, uploadAvatar } from '@/api/user'
import { getFavoritePage } from '@/api/favorite'

const router = useRouter()

// 用户信息
const userInfo = ref({})
const loading = ref(false)
const passwordLoading = ref(false)
const updateLoading = ref(false)
const uploadLoading = ref(false)
const favoritesLoading = ref(false)

// 收藏列表
const favorites = ref([])
const favoritesPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

// 编辑用户信息表单
const editForm = reactive({
  id: '',
  username: '',
  avatar: ''
})

// 编辑模式相关变量已移除

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const loadUserInfo = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    return
  }
  
  try {
    loading.value = true
    const response = await getCurrentUserInfo()
    if (response.code === 200) {
      userInfo.value = response.data
      // 同步到编辑表单
      Object.assign(editForm, {
        id: response.data.id,
        username: response.data.username,
        avatar: response.data.avatar
      })
    } else {
      message.error(response.msg || '获取用户信息失败')
      localStorage.removeItem('token')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    localStorage.removeItem('token')
  } finally {
    loading.value = false
  }
}

// 编辑相关函数已移除，用户名可直接修改

// 保存用户信息
const saveUserInfo = async () => {
  if (!editForm.username.trim()) {
    message.error('用户名不能为空')
    return
  }
  
  try {
    updateLoading.value = true
    const response = await updateUser(editForm)
    if (response.code === 200) {
      message.success('更新成功')
      // 重新获取用户信息
      await loadUserInfo()
    } else {
      message.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息出错:', error)
  } finally {
    updateLoading.value = false
  }
}

// 上传头像
const handleUploadAvatar = async (file) => {
  try {
    uploadLoading.value = true
    const response = await uploadAvatar(file)
    
    if (response.code === 200) {
      // 更新头像URL
      const avatarUrl = response.data
      const updateData = {
        id: userInfo.value.id,
        username: userInfo.value.username,
        avatar: avatarUrl
      }
      
      const updateResponse = await updateUser(updateData)
      if (updateResponse.code === 200) {
        message.success('头像更新成功')
        // 重新获取用户信息
        await loadUserInfo()
      } else {
        message.error('头像更新失败')
      }
    } else {
      message.error('头像上传失败')
    }
  } catch (error) {
    console.error('上传头像出错:', error)
    message.error('头像上传失败')
  } finally {
    uploadLoading.value = false
  }
  
  return false // 阻止默认上传行为
}

// 修改密码
const handleChangePassword = async () => {
  try {
    passwordLoading.value = true
    const response = await changePassword(passwordForm)
    if (response.code === 200) {
      message.success('密码修改成功')
      // 清空表单
      Object.assign(passwordForm, {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    } else {
      message.error(response.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码出错:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 返回首页
const goHome = () => {
  router.push({ name: 'Home' })
}

// 获取收藏列表
const loadFavorites = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    favoritesLoading.value = true
    const response = await getFavoritePage({
      pageNum: favoritesPagination.value.current,
      pageSize: favoritesPagination.value.pageSize
    })
    if (response.code === 200) {
      favorites.value = response.data.records || []
      favoritesPagination.value.total = response.data.total || 0
    } else {
      console.error('获取收藏列表失败:', response.msg)
    }
  } catch (error) {
    console.error('获取收藏列表出错:', error)
  } finally {
    favoritesLoading.value = false
  }
}

// 查看收藏详情
const viewFavoriteDetail = (item) => {
  if (item.caseId) {
    // 跳转到案件详情
    router.push({ name: 'CaseDetail', params: { id: item.caseId } })
  } else if (item.documentId) {
    // 跳转到文档详情
    router.push({ name: 'DocumentDetail', params: { id: item.documentId } })
  }
}

// 页面加载时获取用户信息和收藏列表
onMounted(() => {
  loadUserInfo()
  loadFavorites()
})
</script>

<style>
/* 强制所有元素铺满 */
.ant-spin-container {
  width: 100% !important;
}

.ant-tabs {
  width: 100% !important;
}

.ant-tabs-content {
  width: 100% !important;
}

.ant-tabs-tabpane {
  width: 100% !important;
}

.ant-form {
  width: 100% !important;
}

.ant-form-item {
  width: 100% !important;
}
</style>